package com.tgy.leetcode;

import java.util.*;

/**
 * @Author: tgy
 * @Date: 1/22/21 9:18 AM
 *
 * https://leetcode-cn.com/problems/add-to-array-form-of-integer/
 */
public class _989_数组形式的整数加法 {


    public List<Integer> addToArrayForm(int[] A, int K) {

        int index = A.length - 1;
        List<Integer> res = new ArrayList<>();

        while (index >= 0 || K > 0) {

            K = index >= 0 ? A[index--] + K:K;
            res.add(K % 10);
            K = K / 10;
        }

        Collections.reverse(res);
        return res;
    }

    public List<Integer> addToArrayForm01(int[] A, int K) {

        int index = A.length - 1;
        List<Integer> res = new LinkedList<>();
        int nextBit = 0;

        while (index >= 0 || K > 0) {


            if (K > 0) {

                int bit = K % 10;
                K /= 10;
                int all = bit + nextBit;
                all += (index >= 0 ? A[index]:0);
                nextBit = all / 10;
                res.add(0,all % 10);
            }else {
                if (nextBit > 0) {

                    int all = A[index] + nextBit;
                    nextBit = all / 10;
                    res.add(0,all % 10);
                }else {

                    res.add(0,A[index]);
                }
            }

            index--;
        }

        if (nextBit > 0) {

            res.add(0,nextBit);
        }

        return res;
    }



    public static void main(String[] args) {

        _989_数组形式的整数加法 addToArrayForm = new _989_数组形式的整数加法();

//        int[] nums = {1,2,0,0};
//        int[] nums = {2,7,4};
        int[] nums = {9,9,9,9,9,9,9,9,9,9};
//        int[] nums = {1};
        List<Integer> integers = addToArrayForm.addToArrayForm(nums, 123);
        System.out.println(integers);
    }
}
